//
//  MBRegisterController.m
//  MiBaoTu
//
//  Created by 彭鹏 on 16/9/22.
//  Copyright © 2016年 com.caesartech15. All rights reserved.
//

#import "MBRegisterController.h"
#import "MBNavController.h"
#import "MBRegisterLastController.h"
#import "ErrorMessage.h"
#import "NSString+PJR.h"
#import "NSString+MD5String.h"
#import "Log/NSObject+Log.h"
#import "UserModel.h"
#import "NSString+MD5String.h"
#import <UMMobClick/MobClick.h>
#import "JPLabel.h"
#import "MBSpaceAgreementViewController.h"
@interface MBRegisterController () <JPLabelDelegate,UIGestureRecognizerDelegate>{
    BOOL            isIpad_Registor;
    NSString        *codeStr;
    NSString        *iphoneStr;
}


@property (weak, nonatomic) IBOutlet UIButton *codeBtn;
@property (weak, nonatomic) IBOutlet UIButton *registerBtn;
@property (weak, nonatomic) IBOutlet UIView *phoneView;
@property (weak, nonatomic) IBOutlet UIView *SMSCodeBgView;
@property (weak, nonatomic) IBOutlet UIView *passwordView;
@property (weak, nonatomic) IBOutlet UIView *confirmPasswordView;
@property (weak, nonatomic) IBOutlet UITextField *phoneTF;
@property (weak, nonatomic) IBOutlet UITextField *validateCodeTF;
@property (weak, nonatomic) IBOutlet UITextField *passwordTF;
@property (weak, nonatomic) IBOutlet UITextField *confirmPaswordTF;
@property (weak, nonatomic) IBOutlet UIButton *SMSButton;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *iphoneLeft;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *iphoneRight;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *registorBtRight;
@property (weak, nonatomic) IBOutlet UIView *tipsView;
@property (weak, nonatomic) IBOutlet UIImageView *tipsImgView;

@property (weak, nonatomic) IBOutlet JPLabel *delegateLabel;


@property (weak, nonatomic) IBOutlet UIView *readView;





@end

@implementation MBRegisterController
{
     __block int timeout;
    
}

//获取验证码
- (IBAction)getSMSCode:(id)sender {
    if (![self validateInputIsGetSMSCode:YES]) {//检测输入合法性
        return;
    }
    
    NSString *url = [NSString stringWithFormat:VERIFICATION_PWD_URL_PATH,_phoneTF.text,@"SMS_22385062"];
    [NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]] queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        NSString *str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
        if ([str hasPrefix:@"InvalidSendSmsFrequency limit reaches"]) {
            //失败
            [ErrorMessage showErrorMessage:@"获取失败" inView:self.view];
        } else {
            //成功
            codeStr =  [str substringWithRange:NSMakeRange(str.length-7, 6)];
            iphoneStr = _phoneTF.text;
            [ErrorMessage showErrorMessage:@"短信已下发" inView:self.view];
            [self startTime];
        }
        
    }];
}

-(void)startTime{
    timeout=59; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout<=0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                [_SMSButton setTitle:@"获取验证码" forState:UIControlStateNormal];
                _SMSButton.userInteractionEnabled = YES;
                codeStr = @"";
            });
        }else{
            int seconds = timeout % 60;
            NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                [UIView beginAnimations:nil context:nil];
                [UIView setAnimationDuration:1];
                [_SMSButton setTitle:[NSString stringWithFormat:@"%@秒后重新发送",strTime] forState:UIControlStateNormal];
                [UIView commitAnimations];
                _SMSButton.userInteractionEnabled = NO;
            });
            timeout--;
        }
    });
    dispatch_resume(_timer);
}

//立即注册
- (IBAction)registerNextBtn:(id)sender {
    //跳转
    if (![self validateInputIsGetSMSCode:NO]) {//检测输入合法性
        return;
    }
    if (ISIPAD) {
        if (isIpad_Registor == NO) {
            return;
        }
    }
    if (![codeStr isEqualToString:_validateCodeTF.text]) {
        [ErrorMessage showErrorMessage:@"验证码错误，请重试!" inView:self.view];
        return;
    }
    if (![iphoneStr isEqualToString:_phoneTF.text]) {
        [ErrorMessage showErrorMessage:@"手机号码不一致,请重试!" inView:self.view];
        return;
    }
    
    __weak typeof(self)weakSelf = self;
     [[HTTPManager standerDefault]AFGetRequest:[NSString stringWithFormat:REGISTER_URL_PATH,_phoneTF.text,[NSString stringWithMD5Encrypt:_passwordTF.text]] view:nil success:^(NSDictionary * json) {
        if ([json[@"ret_code"] integerValue]==0) {
            [weakSelf loadDataForLogIn];
        } else {
            [ErrorMessage showErrorMessage:json[@"message"] inView:self.view];
        }
     } failure:^(NSError *error) {
         
     }];
}

//默认登录
- (void)loadDataForLogIn
{
    [[HTTPManager standerDefault]AFGetRequest:[NSString stringWithFormat:LOGIN_URL_PATH,_phoneTF.text,[NSString stringWithMD5Encrypt:_passwordTF.text]] view:nil success:^(NSDictionary * json) {
        if ([json[@"ret_code"] integerValue]==0) {
            //信息保存
            NSDictionary *data = json[@"data"];
            if (data.allKeys.count == 0) return ;
            UserModel *model = [UserModel objectWithKeyValues:data];
            [[UserManager standerDefult] setUserModel:model];
            
            NSArray *collecitonArr = json[@"AudioIDList"];
            if ([collecitonArr isKindOfClass:[NSArray class]]) {
                [[UserManager standerDefult].collectionMusicArr removeAllObjects];
                [[UserManager standerDefult].collectionMusicArr addObjectsFromArray:collecitonArr];
            }
            NSArray *colleciton2Arr = json[@"AlbumIDList"];
            if ([colleciton2Arr isKindOfClass:[NSArray class]]) {
                [[UserManager standerDefult].collectionAlbumArr removeAllObjects];
                [[UserManager standerDefult].collectionAlbumArr addObjectsFromArray:colleciton2Arr];
            }
            NSArray *colleciton3Arr = json[@"ShowIDList"];
            if ([colleciton3Arr isKindOfClass:[NSArray class]]) {
                [[UserManager standerDefult].collectionShowArr removeAllObjects];
                [[UserManager standerDefult].collectionShowArr addObjectsFromArray:colleciton3Arr];
            }
            
            NSArray *praiseListArr = json[@"PraiseList"];
            if ([praiseListArr isKindOfClass:[NSArray class]]) {
                [[UserManager standerDefult].praiseListArr removeAllObjects];
                [[UserManager standerDefult].praiseListArr addObjectsFromArray:praiseListArr];
            }
            
            //保存密码
            NSDate *date = [NSDate date];
            NSDateFormatter  *formatter = [[NSDateFormatter alloc]init];
            [formatter setDateFormat:@"yyyyMMdd"];
            NSString *dateStr = [formatter stringFromDate:date];
            [[NSUserDefaults standardUserDefaults]setObject:[NSString stringWithFormat:@"%@_%@",dateStr,_passwordTF.text] forKey:@"login_answer"];
            [[NSUserDefaults standardUserDefaults]setObject:_phoneTF.text forKey:@"login_phone"];
            [[NSUserDefaults standardUserDefaults]synchronize];
            
            //统计
            [MobClick profileSignInWithPUID:_phoneTF.text];
            
            //跳转
            MBRegisterLastController *registerLastVC = [[MBRegisterLastController alloc] init];
            registerLastVC.title = @"注册";
            registerLastVC.formBaseViewCtrl = _formBaseViewCtrl;
            [self.navigationController pushViewController:registerLastVC animated:YES];
        }
    } failure:^(NSError *error) {
        
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    isIpad_Registor = NO;
    iphoneStr = @"";
    self.view.backgroundColor = [UIColor whiteColor];
//    self.codeBtn.layer.cornerRadius = 5.0;
//    self.codeBtn.clipsToBounds = YES;
    self.registerBtn.layer.cornerRadius = 5.0;
    self.registerBtn.clipsToBounds = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyBoard:)];
    tap.delegate=self;
    [self.view addGestureRecognizer:tap];
    [self setupNavBar];
    
    if (ISIPAD) {
        _iphoneLeft.constant = 600*PERCEN*(self.orientation==UIDeviceOrientationPortrait?1.0*SCREEN_WIDTH/SCREEN_HEIGHT:1.);
        _iphoneRight.constant = 600*PERCEN*(self.orientation==UIDeviceOrientationPortrait?1.0*SCREEN_WIDTH/SCREEN_HEIGHT:1.);
        _registorBtRight.constant = (SCREEN_WIDTH-700*PERCEN*(self.orientation==UIDeviceOrientationPortrait?1.0*SCREEN_WIDTH/SCREEN_HEIGHT:1.))/2.;
        _tipsView.hidden = NO;
    }
    
    UIBezierPath *bezierPath = [UIBezierPath bezierPathWithRoundedRect:_SMSButton.bounds byRoundingCorners:UIRectCornerBottomRight|UIRectCornerTopRight cornerRadii:CGSizeMake(5, 5)];
    CAShapeLayer *layer = [CAShapeLayer layer];
    layer.frame = _SMSButton.bounds;
    layer.path = bezierPath.CGPath;
    _SMSButton.layer.mask = layer;
    
 
    self.delegateLabel.jp_matchArr = @[
                                   @{
                                       @"string" : @"用户协议",
                                       @"color" : UIColorFromHex(0x1e90ff)
                                       }
                                   ];
    
    // 匹配到合适内容的回调
    self.delegateLabel.jp_tapOperation = ^(UILabel *label, HandleStyle style, NSString *selectedString, NSRange range){
        
        // 你想要做的事
        NSLog(@"block打印 %@", selectedString);
        
        if (style == HandleStyleUserDefine) {
            MBSpaceAgreementViewController *web = [MBSpaceAgreementViewController new];
            web.type = AgreementType_Agreen;
            [self.navigationController pushViewController:web animated:YES];
            return ;
        }
    };

    
   
    
    
}
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch

{
    
    CGPoint location = [touch locationInView:self.view];
    
    if(CGRectContainsPoint(self.readView.frame, location))
        
    {
        
        return NO;
        
    }
    
    return YES;
    
}
#pragma mark---JPLabel 协议
-(void)jp_label:(JPLabel *)label didSelectedString:(NSString *)selectedStr forStyle:(HandleStyle)style inRange:(NSRange)range{
    
    // 你想要做的事
    NSLog(@"代理打印 %@", selectedStr);
}


- (void)setupNavBar {
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"fanhui"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]style:UIBarButtonItemStylePlain target:self action:@selector(navigationBackButton)];
}

- (void)onUpdateUIForView:(UIDeviceOrientation)orientation
{
    if (ISIPAD) {
        _iphoneLeft.constant = 600*PERCEN*(self.orientation==UIDeviceOrientationPortrait?1.0*SCREEN_WIDTH/SCREEN_HEIGHT:1.);
        _iphoneRight.constant = 600*PERCEN*(self.orientation==UIDeviceOrientationPortrait?1.0*SCREEN_WIDTH/SCREEN_HEIGHT:1.);
        _registorBtRight.constant = (SCREEN_WIDTH-700*PERCEN*(self.orientation==UIDeviceOrientationPortrait?1.0*SCREEN_WIDTH/SCREEN_HEIGHT:1.))/2.;
        _tipsView.hidden = NO;
    }
}
- (IBAction)onReadTipsAction:(UIButton *)sender {
    sender.selected = !sender.selected;
    if (sender.selected) {
        _tipsImgView.image = [UIImage imageNamed:@"xuanzhong_zl"];
        isIpad_Registor = YES;
    } else {
        _tipsImgView.image = [UIImage imageNamed:@"weixuanzhong_zl"];
        isIpad_Registor = NO;
    }
}

//返回
-(void)navigationBackButton {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)hideKeyBoard:(UITapGestureRecognizer*)tap{
   
    [_phoneTF resignFirstResponder];
    [_passwordTF resignFirstResponder];
    [_validateCodeTF resignFirstResponder];
    [_confirmPaswordTF resignFirstResponder];
}

- (BOOL)validateInputIsGetSMSCode:(BOOL)getSMSCode{
    if ([_phoneTF.text isEqual:@""]) {
        NSLog(@"请输入手机号");
        [ErrorMessage showErrorMessage:@"请输入手机号" inView:self.view];
        return NO;
    }else{
        if (![_phoneTF.text isVAlidPhoneNumber]) {
            NSLog(@"手机号不合法");
            [ErrorMessage showErrorMessage:@"手机号不合法" inView:self.view];
            return NO;
        }
    }
    
    if (getSMSCode) {//获取验证码只需check手机号
        return YES;
    }
    
    if ([_passwordTF.text isEqual:@""]) {
        NSLog(@"请输入密码");
        [ErrorMessage showErrorMessage:@"请输入密码" inView:self.view];
        
        return NO;
    }else{
        if (_passwordTF.text.length<6) {
            NSLog(@"密码长度小于6位");
            [ErrorMessage showErrorMessage:@"密码长度小于6位" inView:self.view];
            
            return NO;
        }
    }
    if ([_validateCodeTF.text isEqual:@""]) {
        NSLog(@"请输入验证码");
        [ErrorMessage showErrorMessage:@"请输入验证码" inView:self.view];
        
        return NO;
    }
    if (![_confirmPaswordTF.text isEqualToString:_passwordTF.text]) {
        NSLog(@"两次密码不一致,请重新输入");
        [ErrorMessage showErrorMessage:@"两次密码不一致,请重新输入" inView:self.view];
        
        return NO;
    }
    
    return YES;
}

#pragma - mark - UITextFieldDelegate
- (void)textFieldDidEndEditing:(UITextField *)textField{
    if (_phoneTF == textField) {
        
    }else if (_passwordTF == textField){
        
    }else{
        
    }
}



@end
